import styles from '../styles.less';
import {Dropdown, Modal, Pagination, Popover, Space, Table, Tag} from 'antd';
import {useCallback, useEffect} from 'react';
import Opera from './Opera';
import {connect, useAccess} from 'umi';
import {DownOutlined, ExclamationCircleFilled} from '@ant-design/icons';
import {nowrapColumns} from '@/utils/utils';

const DataTable = (props) => {

  const {dispatch, dataTable, submitting, loading} = props;
  const {setDataForm, setRecord, tablePayload, setTablePayload} = props.data;
  const access = useAccess();

  /* 获取列表 */
  const fetchList = useCallback((payload) => {
    dispatch({
      type: 'POperationCoupon/fetchList',
      payload: payload,
    });
  }, [dispatch]);

  /* 查询监听 */
  useEffect(() => {
    fetchList(tablePayload);
  }, [fetchList, tablePayload]);

  /* 编辑 */
  function edit(e, record) {
    e.preventDefault();
    setDataForm({
      visible: true,
      title: '编辑操作',
      data: record,
    });
    return false;
  }

  /* 客户列表 */
  function recordList(record) {
    setRecord({
      visible: true,
      title: '领取列表',
      data: record,
    });
  }

  /* 删除 */
  function del(e, record) {
    e.preventDefault();
    if (!submitting) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled/>,
        content: '是否确定删除数据？',
        onOk() {
          dispatch({
            type: 'POperationCoupon/del',
            payload: [record.id],
            callback: () => {
              setTablePayload({...tablePayload, pageNum: 1});
            },
          });
        },
      });
    }
    return false;
  }

  const columns = [
    {
      title: '序号',
      width: 70,
      align: 'center',
      fixed: 'left',
      render: ({}, {}, index) => (
          <span>
          {(tablePayload.pageNum - 1) * tablePayload.pageSize + index + 1}
        </span>
      ),
    },
    {
      title: '卡券类型',
      dataIndex: 'type',
      align: 'center',
      ellipsis: true,
      render: (_, record) => {
        let text = '-';
        if (record.type === 0) {
          text = <span>兑换券</span>;
        }
        if (record.type === 1) {
          text = <span>现金券</span>;
        }
        return text;
      },
    },
    {
      title: '领取方式',
      dataIndex: 'receiveType',
      align: 'center',
      ellipsis: true,
      render: (_, record) => {
        let text = '-';
        if (record.receiveType === 0) {
          text = <span>指定发放</span>;
        }
        if (record.receiveType === 1) {
          text = <span>用户领取</span>;
        }
        return text;
      },
    },
    {
      title: '卡券名称',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '有效时间',
      dataIndex: 'periodTime',
      align: 'center',
    },
    {
      title: '有效期天',
      dataIndex: 'dayNum',
      align: 'center',
    },
    {
      title: '可用商家',
      dataIndex: 'mchCount',
      align: 'center',
      render: (_, record) => {
        if (record.mchCount <= 0) {
          return <span style={{color: '#1d39c4'}}>{record.mchCount}</span>;
        }

        const content = (
            <div>
              {record.couponMchLinkList.map(d => {
                return (<div key={d}>{d.mchName}</div>);
              })}
            </div>
        );
        return (
            <Popover content={content}>
              <span style={{color: '#1d39c4'}}>{record.mchCount}</span>
            </Popover>
        );
      },
    },
    {
      title: '发券商家',
      dataIndex: 'issueMchCount',
      align: 'center',
      render: (_, record) => {
        if (record.issueMchCount <= 0) {
          return <span style={{color: '#1d39c4'}}>{record.issueMchCount}</span>;
        }

        const content = (
            <div>
              {record.issueCouponMchLinkList.map(d => {
                return (<div key={d}>{d.mchName}</div>);
              })}
            </div>
        );
        return (
            <Popover content={content}>
              <span style={{color: '#1d39c4'}}>{record.issueMchCount}</span>
            </Popover>
        );
      },
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      align: 'center',
      ellipsis: true,
      render: (_, record) => {
        return (
            <Tag color={record.status === 1 ? 'geekblue' : 'volcano'}>
              {record.status === 1 ? '正常' : '停用'}
            </Tag>
        );
      },
    },
    {
      title: '排序属性',
      dataIndex: 'orderby',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'option',
      align: 'center',
      width: 160,
      fixed: 'right',
      render: (_, record) => {
        let items = [];
        if (access?.coupon_info_record) {
          items = [...items, {key: 'orders', label: '领取列表', onClick: () => recordList(record)}];
        }
        return (
            <Space size="small">
              {access?.campain_info_edit && (
                  <a onClick={e => edit(e, record)}>编辑</a>
              )}
              {access?.campain_info_del && (
                  <a onClick={e => del(e, record)}>删除</a>
              )}
              {(items.length > 0) && (
                  <Dropdown arrow menu={{items}}>
                    <a onClick={(e) => e.preventDefault()}>
                      更多<DownOutlined/>
                    </a>
                  </Dropdown>
              )}
            </Space>
        );
      },
    },
  ];

  return (
      <>
        <div className={styles.myDataTable}>
          <Opera data={{setDataForm, setRecord}}/>
          <Table
              className={styles.myTable} bordered={false} size={'small'}
              columns={nowrapColumns(columns, dataTable.list)}
              dataSource={dataTable.list} rowKey={'id'}
              pagination={false} scroll={{y: '100%'}} loading={loading}
          />
        </div>
        <Pagination
            pageSize={tablePayload.pageSize} current={tablePayload.pageNum} total={dataTable.total}
            className={styles.myPagination} size={'default'} hideOnSinglePage={false}
            showTotal={(total) => {
              return `共 ${total} 条记录`;
            }}
            pageSizeOptions={[15, 30, 60, 120]}
            showSizeChanger showQuickJumper={true}
            onChange={(page, pageSize) => {
              setTablePayload({...tablePayload, pageNum: page, pageSize: pageSize});
            }}
        />
      </>

  );
};

export default connect(({loading, POperationCoupon}) => {
  return {
    loading: loading.effects['POperationCoupon/fetchList'],
    submitting: loading.effects['POperationCoupon/del'],
    dataTable: POperationCoupon.dataTable,
  };
})(DataTable);
